<!--员工入住 -->
<template>
	<a-modal v-bind="options" :title="props.type === 2 ? '批量入住' : '入住'">
		<a-descriptions v-if="props.type === 1" title="入住人信息" class="ant-descriptions-blockquote">
			<a-descriptions-item label="姓名">{{ tableData.empName }}</a-descriptions-item>
			<a-descriptions-item label="电话">{{ tableData.phone }}</a-descriptions-item>
			<a-descriptions-item label="所属企业">{{ tableData.enterPriseName }}</a-descriptions-item>
		</a-descriptions>
		<a-descriptions v-if="props.type === 2 || props.type === 3" title="企业信息" class="ant-descriptions-blockquote">
			<a-descriptions-item label="企业名称">{{ props.info.enterPriseName }}</a-descriptions-item>
			<a-descriptions-item label="联系人姓名">{{ props.info.linkmanName }}</a-descriptions-item>
			<a-descriptions-item label="联系人电话">{{ props.info.linkmanPhone }}</a-descriptions-item>
		</a-descriptions>
		<a-descriptions>
			<template #title>
				<div class="d-module-title">
					<b>{{ props.type === 1 ? '选择入住房间' : '办理入住' }}</b>
					<div class="select-table">
						<a-input-search enter-button v-model:value="formData.entryName" style="width: 300px" placeholder="房源地址" @search="getNoCheckIn" />
					</div>
				</div>
			</template>
		</a-descriptions>
		<vxe-grid ref="grid" v-bind="gridOptions" :data="tableData.houseRoomDTOList" v-if="props.type === 1">
			<template #houseType="{row}">
				<div>{{ houseType[row.houseType] }}</div>
			</template>
			<!-- <template #actual="{row}">
				<div>{{ row.enterPriseTeamWordDetailsName }}/{{ row.type === 1 ? '折扣' : '满减' }}/{{ discountType[row.discountType] }}/{{ row.discountScale }}%</div>
			</template> -->
			<template #time="{row}">
				<div>{{ row.beginTime }} - {{ row.endTime }}</div>
			</template>
			<template #userlimit="{row}">
				<span>{{ row.userlimit ? (row.userlimit < 10 ? '0' + row.userlimit : row.userlimit) : '-' }}</span>
				/
				<span v-color="{color: !row.userlimit || row.checkInNum > (row.userlimit || 0) ? 'danger' : ''}">{{ row.checkInNum ? (row.checkInNum < 10 ? '0' + row.checkInNum : row.checkInNum) : '-' }}</span>
			</template>
		</vxe-grid>
		<vxe-grid ref="grids" v-bind="gridOptionList" :data="tableData?.houseRoomDTOList || []" v-if="props.type === 2 || props.type === 3">
			<template #houseType="{row}">
				<div>{{ houseType[row.houseType] }}</div>
			</template>
			<template #time="{row}">
				<div>{{ row.beginTime }} - {{ row.endTime }}</div>
			</template>
			<template #staff="{row, rowIndex}">
				<a-select size="middle" style="width: 170px" v-model:value="row.employeeId" :options="staffList" :field-names="{label: 'employeeName', value: 'id'}" placeholder="请选择办理入住的员工" @select="personnelChange(row.employeeId, row, rowIndex)" />
			</template>
			<template #date="{row, rowIndex}">
				<a-date-picker
					v-model:value="row.checkInStartTime"
					placeholder="请选择办理入住时间"
					:value-format="DATE_FORMAT.DATE"
					:disabled-date="(current: Dayjs) => {
    const today = dayjs().endOf('day')
    return (current && current > dayjs(row.endTime).endOf('day')) || (current && current < dayjs(row.beginTime).startOf('day')) || (current && current.isBefore(today, 'date')) || (current && current.isBefore(dayjs(row.beginTime).startOf('day'), 'date'))
}" />
			</template>
		</vxe-grid>

		<!-- <a-typography-paragraph strong>
			<blockquote>物业交割单</blockquote>
		</a-typography-paragraph>
		<div class="width-33">
			<a-button type="primary" block :disabled="!selections.length" @click="deliveryShow">
				<check-outlined v-if="delivery" />
				<plus-outlined v-else />
			</a-button>
		</div> -->
		<template #footer>
			<a-button v-if="props.type !== 2" @click="onCancel">取消</a-button>
			<a-button v-else @click="previousStep">上一步</a-button>
			<a-button type="primary" :loading="loading" @click="onOk">保存</a-button>
		</template>
	</a-modal>
	<delivery-note v-if="options.visible" @success="data => (delivery = data)" v-model:visible="record.delivery" :isShow="props.type === 2" :id="selections[0]?.id || ''" />
	<batch-delivery-note v-model:visible="record.batchDelivery" :house-list="selections" />
	<!-- 通行授权弹窗 -->
	<!--<access-authorization-dialog v-model:visible="visibles.accessAuth" :device-detail="deviceDetail" :hydropower="isShowHydropower" @success="onCancel" /> -->
	<access-authorization-rewrite-dialog :houseInfoArr="houseInfoArr" v-model:visible="visibles.accessAuth" @success="onCancel" />
</template>

<script setup lang="ts">
	import {reactive, ref, toRef, watch, createVNode} from 'vue'
	import DeliveryNote from '@/components/contract/add-tenant-contract-dialog/delivery-note.vue'
	import BatchDeliveryNote from '@/components/contract/enterprise-customer-management/batch-delivery-note.vue'
	import {staffCheckIn, noCheckIn, employeeList, batchCheckInHouse} from '@/api/staff-pool'
	import {CheckOutlined, PlusOutlined, ExclamationCircleOutlined} from '@ant-design/icons-vue'
	import {VxeGridInstance, VxeGridProps} from 'vxe-table'
	import {RenterContractDevice} from '@/interface/contract'
	import {renterContractEnterDevice} from '@/api/contract'
	import DATE_FORMAT from 'yuxin-base/src/utils/date'
	import XEUtils from 'xe-utils'
	import dayjs, {Dayjs} from 'dayjs'
	import {message, Modal} from 'ant-design-vue'
	import {any} from 'vue-types'
	import {getBatchDeviceAuth} from '@/api/device'
	import AccessAuthorizationDialog from '@/components/contract/add-tenant-contract-dialog/access-authorization-dialog.vue'
	import AccessAuthorizationRewriteDialog from '@/components/contract/add-tenant-contract-dialog/access-authorization-rewrite-dialog.vue'
	const emits = defineEmits(['update:visible', 'close'])
	interface Department {
		id?: string | number | null
		type: string | number | null
		enterPriseName?: string | null
		linkmanName?: string | null
		linkmanPhone?: string | null
	}
	const discountType = ref({
		1: '每月折 ',
		2: '首月折 ',
		3: '尾月折 '
	})

	const props = defineProps<{
		visible: boolean
		id: string | number
		type: string | number | null
		info?: Department | object | null
	}>()
	const formData = reactive<any>({
		entryName: null
	})
	// 物业交割单
	const delivery = ref<any>()
	const enterprisesOptions = reactive([
		{
			label: '全部',
			value: ''
		},
		{
			label: '集中',
			value: 3
		},
		{
			label: '整租',
			value: 1
		},
		{
			label: '合租',
			value: 2
		}
	])
	const houseType = {
		1: '整租',
		2: '合租',
		3: '集中'
	}
	const selections = ref<any>([])
	const gridOptions = reactive<VxeGridProps>({
		height: '300',
		showOverflow: true,
		rowConfig: {
			height: 60,
			isHover: true
		},
		onRadioChange({row}: any) {
			if (row.checkInNum >= (row.userlimit || 0)) {
				Modal.warning({
					title: '提示',
					centered: true,
					icon: createVNode(ExclamationCircleOutlined),
					content: '该房间实际入住数已高于设定入住数，请确认是否仍要办理入住'
				})
			}
			selections.value.push(row)
		},
		columns: [
			{
				width: 50,
				title: '',
				align: 'center',
				fixed: 'left',
				type: 'radio'
			},
			{
				title: '房源地址',
				field: 'address',
				minWidth: 260
			},
			{
				title: '租金',
				field: 'actualPrice',
				minWidth: 80,
				align: 'right'
			},
			// {
			// 	title: '租金协议价',
			// 	slots: {default: 'actual'},
			// 	align: 'right',
			// 	minWidth: 150
			// },
			{
				title: '合同周期',
				slots: {default: 'time'},
				minWidth: 220,
				align: 'center'
			},
			{
				title: '设定入住数/实际入住数',
				slots: {default: 'userlimit'},
				minWidth: 220,
				align: 'center'
			}
		]
	})
	const gridOptionList = reactive<VxeGridProps>({
		height: '300',
		showOverflow: true,
		rowConfig: {
			height: 60,
			isHover: true
		},
		columns: [
			{
				title: '所属项目',
				field: 'communityName',
				width: 150,
				align: 'left'
			},
			{
				title: '房源类型',
				// dataIndex: 'amount',
				width: 150,
				align: 'left',
				slots: {default: 'houseType'}
			},
			{
				title: '房源地址',
				field: 'address',
				minWidth: 260,
				align: 'left'
			},
			{
				title: '租金',
				field: 'actualPrice',
				minWidth: 150,
				align: 'right'
			},
			{
				title: '合同周期',
				slots: {default: 'time'},
				minWidth: 300,
				align: 'center'
			},
			{
				title: '入住员工',
				// editRender: {name: 'select'},
				slots: {default: 'staff'},
				fixed: 'right',
				width: 200,
				align: 'left'
			},
			{
				title: '入住日期',
				slots: {default: 'date'},
				fixed: 'right',
				width: 150,
				align: 'left'
			}
		]
	})
	const oldValue = reactive<any>({
		name: null,
		id: null,
		index: null
	})
	const personnelChange = (value, row, rowIndex) => {
		console.log('rowIndex:', value, rowIndex)
		if (value) {
			if (oldValue.id === value && oldValue.index === rowIndex) {
				return
			}
			if (selections.value.length) {
				let index = selections.value.findIndex(o => o.employeeId === row.employeeId && o.id !== row.id)
				if (index !== -1) {
					message.error('该员工已选择其他房间，请重新选择')
					tableData.value.houseRoomDTOList[rowIndex].employeeName = null
					tableData.value.houseRoomDTOList[rowIndex].employeeId = null
					spliceList(row.id)
					return
				}
				pushDate(value, row, rowIndex)
			} else {
				pushDate(value, row, rowIndex)
			}
		} else {
			spliceList(row.id)
		}
	}
	const spliceList = id => {
		let index = selections.value.findIndex(o => o.id === id)
		if (index !== -1) {
			selections.value.splice(index, 1)
		}
	}
	const pushDate = (value, row, rowIndex) => {
		oldValue.id = value
		oldValue.index = rowIndex
		oldValue.name = staffList.value.filter(o => o.id === value)[0]?.employeeName || ''
		tableData.value.houseRoomDTOList[rowIndex].employeeName = oldValue.name
		selections.value.push(row)
	}
	const grid = ref()
	const grids = ref()
	const staffList = ref<any>([])
	const record = reactive({
		delivery: false,
		batchDelivery: false,
		isShow: false
	})
	const data = ref({
		meters: [],
		articles: []
	})

	const getList = (page?: any) => {
		grid.value.commitProxy(page === 1 ? 'reload' : 'query')
	}
	const tableData = ref<any>({})
	const options = reactive({
		width: 1100,
		centered: true,
		maskClosable: false,
		destroyOnClose: true,
		key: Math.random(),
		visible: toRef(props, 'visible'),
		okText: '确认入住',
		onCancel() {
			onCancel()
		}
	})
	const onCancel = () => {
		formData.entryName = null
		previousStep()
		setTimeout(() => {
			emits('close')
			emits('update:visible', false)
		}, 100)
	}
	const previousStep = () => {
		loading.value = false
		selections.value = []
		delivery.value = null
		oldValue.index = null
		oldValue.id = null
	}
	const loading = ref(false)
	const onOk = () => {
		// if (delivery.value) {
		loading.value = true
		if (props.type === 1 || props.type === 3) {
			//单个入住
			setStaffCheckIn()
		} else {
			//批量入住
			setBatchCheckInHouse()
		}
		// } else {
		// message.error('请先填写物业交割单')
		// }
	}
	//保存单个员工入住
	const setStaffCheckIn = () => {
		if (selections.value.length > 0) {
			let newDelivery = delivery.value ? JSON.parse(JSON.stringify(delivery.value)) : ''
			let params = {
				...newDelivery,
				deliveryType: 1,
				compactType: 2,
				communityName: selections.value[0].communityName,
				charterMoney: selections.value[0].actualPrice,
				houseAddress: selections.value[0].address,
				houseId: selections.value[0].id,
				houseType: selections.value[0].houseType,
				compactId: selections.value[0].contractId,
				enterPriseContractId: selections.value[0].enterPriseContractId,
				enterEmployeeId: props.type === 1 ? props.id : selections.value[0].employeeId,
				checkInEndTime: selections.value[0].endTime,
				checkInStartDateTime: selections.value[0].checkInStartTime || dayjs(new Date()).format('YYYY-MM-DD')
			}
			delete params?._X_ROW_KEY
			staffCheckIn(params)
				.then(res => {
					// message.success('操作成功')
					// emits('update:visible', false)
					// setTimeout(() => emits('close'), 100)
					// 这里也是走批量下发授权 不过数组长度为1
					batchDeviceAccessAuth(selections.value)
					// deviceAccessAuth(selections.value[0].contractId, params.enterEmployeeId)
				})
				.finally(() => (loading.value = false))
		} else {
			message.error('请选择入住的房间')
			loading.value = false
		}
	}
	//保存多个员工
	const setBatchCheckInHouse = () => {
		if (selections.value.length > 0) {
			let charterContractFromList: any = []
			for (let item of selections.value) {
				let newDelivery = delivery.value ? JSON.parse(JSON.stringify(delivery.value)) : ''
				let params = {
					...newDelivery,
					deliveryType: 1,
					compactType: 2,
					communityName: item.communityName,
					charterMoney: item.actualPrice,
					houseAddress: item.address,
					houseId: item.id,
					houseType: selections.value[0].houseType,
					compactId: item.contractId,
					enterPriseContractId: item.enterPriseContractId,
					enterEmployeeId: item.employeeId,
					checkInEndTime: item.endTime,
					checkInStartDateTime: item.checkInStartTime || dayjs(new Date()).format('YYYY-MM-DD')
				}
				delete params?._X_ROW_KEY
				charterContractFromList.push(params)
			}
			batchCheckInHouse({charterContractFromList})
				.then(res => {
					// 批量下发授权
					batchDeviceAccessAuth(selections.value)
					// message.success('操作成功')
					// emits('update:visible', false)
					// setTimeout(() => emits('close'), 100)
				})
				.finally(() => (loading.value = false))
		} else {
			message.error('请选择入住的房间')
			loading.value = false
		}
	}
	// 批量下发授权(保存的时候根据接口校验,单个的也走批量的逻辑 只是数组里只有一项)
	const houseInfoArr = ref([])
	const batchDeviceAccessAuth = (selectionArr: Array<any>) => {
		const params = selectionArr.map(i => {
			return {id: i.contractId, houseId: i.id, enterpriseEmployeeIds: [props.type === 1 ? props.id : i.employeeId]}
		})
		getBatchDeviceAuth(params).then(({data}) => {
			data.forEach(i => {
				i.sourceType = 2
				;(i.renterInfos || []).forEach(j => {
					j.accessAuthType = []
					j.lockAuthType = []
				})
			})
			houseInfoArr.value = data || []
			if (!data.map(i => i.showAccessLock).includes(true)) {
				message.success('操作成功')
				onCancel()
			} else if (data.map(i => i.hasLock).includes(true) || data.map(i => i.hasAccess).includes(true)) {
				visibles.accessAuth = true
			} else {
				message.success('操作成功')
				onCancel()
			}
		})
	}

	const visibles = reactive({
		accessAuth: false
	})
	//通行授权是否展示水电 续签则不展示
	const isShowHydropower = ref<boolean>(false)
	// 智能设备通行授权
	const deviceDetail = ref<RenterContractDevice>({} as RenterContractDevice)
	const deviceAccessAuth = (contractId: string, empId: string) => {
		if (contractId) {
			renterContractEnterDevice(contractId, empId).then(({data}) => {
				data.renterInfos.forEach((item: any) => {
					item.accessAuthType = []
					item.lockAuthType = []
				})
				deviceDetail.value = data
				if (!deviceDetail.value.showAccessLock) {
					onCancel()
				} else if (deviceDetail.value.hasLock || deviceDetail.value.hasAccess) {
					visibles.accessAuth = true
					deviceDetail.value.sourceType = 2
				} else {
					onCancel()
				}
			})
		}
	}
	//物业交割单点击事件
	const deliveryShow = () => {
		if (props.type === 2) {
			record.batchDelivery = true
		} else {
			record.delivery = true
		}
	}
	const getNoCheckIn = () => {
		selections.value = []
		tableData.value = []
		let like = props.type === 3 ? props?.info.fullAddress : formData.entryName,
			params = props.type === 1 ? {id: props.id, like} : {enterPriseId: props.id, like}
		noCheckIn(params).then(res => {
			if (props.type !== 1 && res.data.houseRoomDTOList) {
				tableData.value.houseRoomDTOList = []
				for (let item of res.data.houseRoomDTOList) {
					if (item.checkInNum <= 20) {
						// 筛选人数小于20的房间
						tableData.value.houseRoomDTOList.push({
							...item,
							employeeId: null,
							employeeName: null,
							checkInStartTime: null
						})
					}
				}
			} else {
				tableData.value = res.data
				// 筛选人数小于20的房间
				tableData.value.houseRoomDTOList = (res.data?.houseRoomDTOList || []).filter(i => i.checkInNum <= 20)
			}
		})
	}
	//获取员工
	const getEmployeeList = () => {
		let params = {
			enterPriseId: props.id,
			statusList: [1, 2],
			current: 1,
			size: 999
		}
		employeeList(params).then(res => {
			staffList.value = res.data.records || []
		})
	}
	watch(
		() => props.visible,
		newVal => {
			if (newVal && props.type && props.id) {
				getNoCheckIn()
				if (props.type !== 1) {
					getEmployeeList()
				}
			}
		}
	)
</script>

<style lang="less" scoped>
	.d-module-title {
		position: relative;
		height: 40px;

		.width-33 {
			width: 33.33%;
		}

		.select-table {
			position: absolute;
			right: 0;

			:deep(.ant-btn-icon-only) {
				border-left: transparent;
			}
		}

		.ant-select {
			width: 100%;
		}
	}
</style>
